package com.fulizhe.catlocal.integration.okhttp.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import com.dianping.cat.Cat;
import com.dianping.cat.local.integration.servlet.CatMsgConstants;
import com.dianping.cat.local.integration.servlet.CatMsgContext;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

@RestController
public class HelloController {

	@Autowired
	private ServerProperties sp;

	@GetMapping("/hello")
	public String index(HttpServletRequest request) {
		LoggerFactory.getLogger(this.getClass()).info("开始OkHttp调用....");

		httpTest();

		return String.format(
				"<br><br> 当前请求的TraceId为 [ <strong> <a target=\"_blank\" href=\"./cat/cat.html?traceId=%s\">%s</a> </strong> ] <--- 点击左侧链接跳转到'CAT-LOCAL链路查询页面'查看链路日志 <br><br><br> %s", //
				Cat.getCurrentMessageId(), Cat.getCurrentMessageId(),
				"查看traceId来源, 请打开F12, 然后刷新页面, 在返回HTTP Header中有一个名为X-ROOT-TRACE-ID的key");
	}

	@GetMapping("/calledRemoteService")
	public String index2(HttpServletRequest request) {
		LoggerFactory.getLogger(this.getClass()).info("被OkHttp Invoke....");

		return "Invoked By OkHttp";
	}

	String httpTest() {
		final String url = String.format("http://127.0.0.1:%s/calledRemoteService", sp.getPort());

		createMessageTree();

		final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
		final String rootId = requestAttributes.getAttribute(Cat.Context.ROOT, 0).toString();
		final String childId = requestAttributes.getAttribute(Cat.Context.CHILD, 0).toString();
		final String parentId = requestAttributes.getAttribute(Cat.Context.PARENT, 0).toString();

		OkHttpClient okHttpClient = new OkHttpClient().newBuilder().addInterceptor(new Interceptor() {
			@Override
			public Response intercept(Chain chain) throws IOException {
				Request request = chain.request();

				okhttp3.Headers.Builder headerBuilder = request.headers().newBuilder();
				headerBuilder.add(Cat.Context.ROOT, rootId);
				headerBuilder.add(Cat.Context.CHILD, childId);
				headerBuilder.add(Cat.Context.PARENT, parentId);
				headerBuilder.add(CatMsgConstants.APPLICATION_KEY, Cat.getManager().getDomain());

				okhttp3.Request.Builder requestBuilder = request.newBuilder();
				requestBuilder.headers(headerBuilder.build());

				return chain.proceed(requestBuilder.build());
			}
		}).build();

		Request request = new Request.Builder().url(url).get().build();
		// 获取响应并把响应体返回
		try (Response response = okHttpClient.newCall(request).execute()) {
			return response.body().string();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 统一设置消息编号的messageId
	 */
	private void createMessageTree() {
		LoggerFactory.getLogger(this.getClass()).debug("统一设置消息编号的messageId");
		final CatMsgContext context = new CatMsgContext();
		Cat.logRemoteCallClient(context);
		RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
		requestAttributes.setAttribute(Cat.Context.PARENT, context.getProperty(Cat.Context.PARENT), 0);
		requestAttributes.setAttribute(Cat.Context.ROOT, context.getProperty(Cat.Context.ROOT), 0);
		requestAttributes.setAttribute(Cat.Context.CHILD, context.getProperty(Cat.Context.CHILD), 0);
		requestAttributes.setAttribute(CatMsgConstants.APPLICATION_KEY, Cat.getManager().getDomain(), 0);
	}

}